package com.lvmama.controller.rhino.order;

import com.alibaba.fastjson.JSONArray;
import com.lvmama.common.enums.CommonParentType;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.pojo.entity.rhino.order.OrderInfo;
import com.lvmama.service.rhino.order.OrderService;
import com.lvmama.service.rhino.topic.StatisticCodeService;
import com.lvmama.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderAnalysisController {


    @Autowired
    private OrderService orderService;
    @Autowired
    private StatisticCodeService statisticCodeService;

    /**
     * 订单图表数据
     *
     * @param
     * @param chooseTime
     * @return
     * @throws Exception
     */
    @PostMapping("/orderChartData")
    @ResponseBody
    public Result<Map<String, Object>> orderChartData(@RequestParam("chooseTime")String chooseTime, @RequestParam("userUseYear")String userUseYear, @RequestParam("flag")String flag) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        OrderInfo order = new OrderInfo();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        order.setStartDate(beginDate);
        order.setEndDate(endDate);
        order.setUserUseYear(userUseYear);
        try {
            List<OrderInfo> lineChartlist = orderService.getListByDate(order);
            List<OrderInfo> columarChartlist = orderService.getListByCategory(order);
            // 柱状图数据
            List<String> categoryList = new ArrayList<>();
            JSONArray orderAmountArr2 = new JSONArray();
            JSONArray orderMoneyArr2 = new JSONArray();
            for (OrderInfo orderInfo : columarChartlist) {
                if(StringUtils.isNotEmpty(CommonParentType.getCategoryShowName(orderInfo.getCategoryId()))){
                    categoryList.add(CommonParentType.getCategoryShowName(orderInfo.getCategoryId()));
                    JSONObject orderAmountObj = new JSONObject();
                    orderAmountObj.put("categoryName",CommonParentType.getCategoryShowName(orderInfo.getCategoryId()));
                    JSONObject orderMoneyObj = new JSONObject();
                    orderMoneyObj.put("categoryName",CommonParentType.getCategoryShowName(orderInfo.getCategoryId()));
                    if ("order_num".equals(flag)) {
                        orderAmountObj.put("amount",orderInfo.getOrderAmount());
                    } else {
                        orderMoneyObj.put("amount",new BigDecimal(orderInfo.getOrderMoney()).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                    }
                    orderAmountArr2.add(orderAmountObj);
                    orderMoneyArr2.add(orderMoneyObj);
                }
            }
            // 折线图数据
            String[] dateAxis = DateUtil.getBetweenTime(beginDate, endDate, "yyyy/MM/dd");
            List<String> dateList = Arrays.asList(dateAxis);
            JSONArray orderAmountArr = new JSONArray();
            JSONArray orderMoneyArr = new JSONArray();
            for(String date:dateList){
                for (String category : categoryList) {
                    Integer orderAmountTomal = 0;
                    Double orderMoneyTomal = 0.0;
                    for (OrderInfo orderInfo : lineChartlist) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                        String time = sdf.format(orderInfo.getOperDate());
                        if (category.equals(CommonParentType.getCategoryShowName(orderInfo.getCategoryId())) && date.equals(time)) {
                            orderAmountTomal += orderInfo.getOrderAmount();
                            orderMoneyTomal += new BigDecimal(orderInfo.getOrderMoney()).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                        }
                    }
                    JSONObject orderAmountObj = new JSONObject();
                    orderAmountObj.put("categoryName",category);
                    orderAmountObj.put("time",date);
                    orderAmountObj.put("amount",orderAmountTomal);
                    orderAmountArr.add(orderAmountObj);
                    JSONObject orderMoneyObj = new JSONObject();
                    orderMoneyObj.put("categoryName",category);
                    orderMoneyObj.put("time",date);
                    orderMoneyObj.put("amount",orderMoneyTomal);
                    orderMoneyArr.add(orderMoneyObj);
                }
            }
            resultMap.put("categoryList", categoryList);
            resultMap.put("dateAxis", dateAxis);
            if ("order_num".equals(flag)) {
                resultMap.put("orderAmountJson", orderAmountArr);
                resultMap.put("orderAmountJson2", orderAmountArr2);
            } else {
                resultMap.put("orderMoneyJson2", orderMoneyArr2);
                resultMap.put("orderMoneyJson", orderMoneyArr);
            }
        } catch (Exception e) {
            log.error("orderChartData error{}",e);
        }

        return Result.success(resultMap);
    }


    @PostMapping("/orderDataByCategory")
    @ResponseBody
    public Result<Map<String, Object>> orderDataByCategory(@RequestParam("chooseTime")String chooseTime,
                                                           @RequestParam("userUseYear")String userUseYear, @RequestParam("flag")String flag, @RequestParam("categoryName")String categoryName) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        OrderInfo order = new OrderInfo();
        // 查询日期条件处理
        Map<String, Date> dateMap = ToolUtils.getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        order.setStartDate(beginDate);
        order.setEndDate(endDate);
        order.setUserUseYear(userUseYear);
        order.setCategoryId(CommonParentType.getCategoryValueByShowName(categoryName));
        try {
            List<OrderInfo> orderlist = orderService.getListByPerform(order);
            if ("order_num".equals(flag)) {
                resultMap = getAmountMapByPlatform(orderlist);
            } else {
                resultMap = getMoneyMapByPlatform(orderlist);
            }
        } catch (Exception e) {
            log.error("orderDataByCategory error{}",e);
        }
        return Result.success(resultMap);
    }


    private Map<String, Object> getAmountMapByPlatform(List<OrderInfo> orderlist) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // pc,wap有两级渠道 app只有一级下载渠道
        Map<String, Integer> iosFirstChennelMap = new HashMap<String, Integer>();
        Map<String, Integer> androidFirstChennelMap = new HashMap<String, Integer>();
        // pc,wap
        String[] firstChannelArr = { "直接", "SEO", "SEM", "分享" };
        int[] firstAmountArr = new int[4];
        Map<String, Integer> SEOChennelMap = new HashMap<String, Integer>();
        Map<String, Integer> SEMChennelMap = new HashMap<String, Integer>();
        Map<String, Integer> shareChennelMap = new HashMap<String, Integer>();

        for (OrderInfo orderInfo : orderlist) {
            String orderJson = orderInfo.getOrderAmountJson();
            int orderAmount = 0;
            if (StringUtils.isNotBlank(orderJson)) {
                JSONObject jsonObject = JSONObject.fromObject(orderJson);
                for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
                    String channelCode = (String) iter.next();
                    int channelAmount = jsonObject.getInt(channelCode);
                    orderAmount += channelAmount;
                    if ("pc".equals(orderInfo.getPlatformCode()) || "wap".equals(orderInfo.getPlatformCode())) {
                        String channelName = statisticCodeService.getNameByCode(channelCode).getName();
                        if (channelCode.equals("116yq5")) {
                            firstAmountArr[0] += orderAmount;
                        } else if (channelCode.startsWith("123")) {
                            firstAmountArr[1] += orderAmount;
                            if (SEOChennelMap.containsKey(channelName)) {
                                orderAmount += SEOChennelMap.get(channelName);
                            }
                            SEOChennelMap.put(channelName, orderAmount);
                        } else if (channelCode.startsWith("12h")) {
                            firstAmountArr[2] += orderAmount;
                            if (SEMChennelMap.containsKey(channelName)) {
                                orderAmount += SEMChennelMap.get(channelName);
                            }
                            SEMChennelMap.put(channelName, orderAmount);
                        } else if (channelCode.startsWith("121")) {
                            firstAmountArr[3] += orderAmount;
                            if (shareChennelMap.containsKey(channelName)) {
                                orderAmount += shareChennelMap.get(channelName);
                            }
                            shareChennelMap.put(channelName, orderAmount);
                        }
                    } else if ("ios".equals(orderInfo.getPlatformCode())) {
                        if (iosFirstChennelMap.containsKey(channelCode)) {
                            channelAmount += iosFirstChennelMap.get(channelCode);
                        }
                        iosFirstChennelMap.put(channelCode, channelAmount);
                    } else {
                        if (androidFirstChennelMap.containsKey(channelCode)) {
                            channelAmount += androidFirstChennelMap.get(channelCode);
                        }
                        androidFirstChennelMap.put(channelCode, channelAmount);
                    }
                }
            }
        }
        // 获取前十条数据
        iosFirstChennelMap = ToolUtils.sortByValueDesc(iosFirstChennelMap);
        androidFirstChennelMap = ToolUtils.sortByValueDesc(androidFirstChennelMap);
        int i = 0;
        int amount = 0;
        JSONArray iosJsonArr = new JSONArray();
        for (Map.Entry<String, Integer> entry : iosFirstChennelMap.entrySet()) {
            if (i < 10) {
                JSONObject o = new JSONObject();
                o.put("name",entry.getKey());
                o.put("value",entry.getValue());
                iosJsonArr.add(o);
            } else {
                amount += entry.getValue();
            }
            i++;
        }
        if (iosFirstChennelMap.size() > 10) {
            JSONObject o = new JSONObject();
            o.put("name","其他");
            o.put("value",amount);
            iosJsonArr.add(o);
        }
        i = 0;
        amount = 0;
        JSONArray androidJsonArr = new JSONArray();
        for (Map.Entry<String, Integer> entry : androidFirstChennelMap.entrySet()) {
            if (i < 10) {
                JSONObject o = new JSONObject();
                o.put("name",entry.getKey());
                o.put("value",entry.getValue());
                androidJsonArr.add(o);
            } else {
                amount += entry.getValue();
            }
            i++;
        }
        if (androidFirstChennelMap.size() > 10) {
            JSONObject o = new JSONObject();
            o.put("name","其他");
            o.put("value",amount);
            androidJsonArr.add(o);
        }

        resultMap.put("androidJsonArr", androidJsonArr);
        resultMap.put("iosJsonArr", iosJsonArr);
        resultMap.put("firstChannelArr", firstChannelArr);
        resultMap.put("firstAmountArr", firstAmountArr);
        resultMap.put("SEOChennelMap", JSONObject.fromObject(SEOChennelMap).toString());
        resultMap.put("SEMChennelMap", JSONObject.fromObject(SEMChennelMap).toString());
        resultMap.put("shareChennelMap", JSONObject.fromObject(shareChennelMap).toString());
        return resultMap;
    }


    private Map<String, Object> getMoneyMapByPlatform(List<OrderInfo> orderlist) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // pc,wap有两级渠道 app只有一级下载渠道
        Map<String, Double> iosFirstChennelMap = new HashMap<String, Double>();
        Map<String, Double> androidFirstChennelMap = new HashMap<String, Double>();
        // pc,wap
        String[] firstChannelArr = { "直接", "SEO", "SEM", "分享" };
        double[] firstAmountArr = new double[4];
        Map<String, Double> SEOChennelMap = new HashMap<String, Double>();
        Map<String, Double> SEMChennelMap = new HashMap<String, Double>();
        Map<String, Double> shareChennelMap = new HashMap<String, Double>();

        for (OrderInfo orderInfo : orderlist) {
            String orderJson = orderInfo.getOrderMoneyJson();
            double orderAmount = 0;
            if (StringUtils.isNotBlank(orderJson)) {
                JSONObject jsonObject = JSONObject.fromObject(orderJson);
                for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
                    String channelCode = (String) iter.next();
                    double channelAmount = jsonObject.getDouble(channelCode);
                    orderAmount += channelAmount;
                    if ("pc".equals(orderInfo.getPlatformCode())
                            || "wap".equals(orderInfo.getPlatformCode())) {
                        String channelName = statisticCodeService.getNameByCode(channelCode).getName();
                        if (channelCode.equals("116yq5")) {
                            firstAmountArr[0] += orderAmount;
                        } else if (channelCode.startsWith("123")) {
                            firstAmountArr[1] += orderAmount;
                            if (SEOChennelMap.containsKey(channelName)) {
                                orderAmount += SEOChennelMap.get(channelName);
                            }
                            SEOChennelMap.put(
                                    channelName,
                                    new BigDecimal(orderAmount).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                        } else if (channelCode.startsWith("12h")) {
                            firstAmountArr[2] += orderAmount;
                            if (SEMChennelMap.containsKey(channelName)) {
                                orderAmount += SEMChennelMap.get(channelName);
                            }
                            SEMChennelMap.put(
                                    channelName,
                                    new BigDecimal(orderAmount).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                        } else if (channelCode.startsWith("121")) {
                            firstAmountArr[3] += orderAmount;
                            if (shareChennelMap.containsKey(channelName)) {
                                orderAmount += shareChennelMap.get(channelName);
                            }
                            shareChennelMap.put(
                                    channelName,
                                    new BigDecimal(orderAmount).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                        }
                    } else if ("ios".equals(orderInfo.getPlatformCode())) {
                        if (iosFirstChennelMap.containsKey(channelCode)) {
                            channelAmount += iosFirstChennelMap
                                    .get(channelCode);
                        }
                        iosFirstChennelMap.put(
                                channelCode,
                                new BigDecimal(channelAmount).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                    } else {
                        if (androidFirstChennelMap.containsKey(channelCode)) {
                            channelAmount += androidFirstChennelMap.get(channelCode);
                        }
                        androidFirstChennelMap.put(
                                channelCode,
                                new BigDecimal(channelAmount).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                    }
                }
            }
        }
        // 获取前十条数据
        iosFirstChennelMap = ToolUtils.sortByValueDesc(iosFirstChennelMap);
        androidFirstChennelMap = ToolUtils.sortByValueDesc(androidFirstChennelMap);
        JSONArray iosJsonArr = new JSONArray();
        JSONArray androidJsonArr = new JSONArray();
        int i = 0;
        double amount = 0;
        for (Map.Entry<String, Double> entry : iosFirstChennelMap.entrySet()) {
            if (i < 10) {
                JSONObject o = new JSONObject();
                o.put("name",entry.getKey());
                o.put("value",entry.getValue());
                iosJsonArr.add(o);
            } else {
                amount += entry.getValue();
            }
            i++;
        }
        if (iosFirstChennelMap.size() > 10) {
            JSONObject o = new JSONObject();
            o.put("name","其他");
            o.put("value",amount);
            iosJsonArr.add(o);
        }
        i = 0;
        amount = 0;
        for (Map.Entry<String, Double> entry : androidFirstChennelMap
                .entrySet()) {
            if (i < 10) {
                JSONObject o = new JSONObject();
                o.put("name",entry.getKey());
                o.put("value",entry.getValue());
                androidJsonArr.add(o);
            } else {
                amount += entry.getValue();
            }
            i++;
        }
        if (androidFirstChennelMap.size() > 10) {
            JSONObject o = new JSONObject();
            o.put("name","其他");
            o.put("value",amount);
            androidJsonArr.add(o);
        }

        resultMap.put("androidJsonArr", androidJsonArr);
        resultMap.put("iosJsonArr", iosJsonArr);
        resultMap.put("firstChannelArr", firstChannelArr);
        resultMap.put("firstAmountArr", firstAmountArr);
        resultMap.put("SEOChennelMap", JSONObject.fromObject(SEOChennelMap).toString());
        resultMap.put("SEMChennelMap", JSONObject.fromObject(SEMChennelMap).toString());
        resultMap.put("shareChennelMap", JSONObject.fromObject(shareChennelMap).toString());
        return resultMap;
    }




}
